var express = require('express');
var router = express.Router();
var commonImportService = require('../../service/excel/CommonImportService')
var commonExportService = require('../../service/excel/CommonExportService')

var fs = require('fs');
var multer  = require('multer');

// 使用硬盘存储模式设置存放接收到的文件的路径以及文件名
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
      // 接收到文件后输出的保存路径（若不存在则需要创建）
      cb(null, 'upload/');    
  },
  filename: function (req, file, cb) {
      // 将保存文件名设置为 时间戳 + 文件原始名，比如 151342376785-123.jpg
      cb(null, Date.now() + "-" + file.originalname);  
  }
});

// 创建文件夹
var createFolder = function(folder){
  try{
      // 测试 path 指定的文件或目录的用户权限,我们用来检测文件是否存在
      // 如果文件路径不存在将会抛出错误"no such file or directory"
      fs.accessSync(folder); 
  }catch(e){
      // 文件夹不存在，以同步的方式创建文件目录。
      fs.mkdirSync(folder);
  }  
};

var uploadFolder = './upload/';
createFolder(uploadFolder);

// 创建 multer 对象
var upload = multer({ storage: storage });


/**
 * 通用导出.
 * params {
 *   tableName: "",
 *   enumTypes: [],
 *   tableConfigs: []
 *   header: [
 *     { title: '序号', width: 10,  },
 *     { title: '序号', width: 10, ext: { prop: 'userName', type: 'index|enum|table|default|custom|date', func: '', key: 'BUG_REASON', value: 'email', label: 'userName' } }
 *   ],
 *   condition: {}
 * }
 */
router.post('/common/export', function (req, res, next) {
  var params = req.body;
  commonExportService.getExcel(params).then((workbook) => {
    res.setHeader('Content-Type', 'application/vnd.openxmlformats');
    res.setHeader("Content-Disposition", "attachment; filename=default.xlsx");
    workbook.xlsx.write(res).then(() => {
      res.end();
    }).catch((err) => {
      res.send(err)
    })
  })
});

/**
 * 通用导入.
 * params {
 *   tableName: "",
 *   enumTypes: [],
 *   tableConfigs: []
 *   header: [
 *     { title: '序号', width: 10,  },
 *     { title: '序号', width: 10, ext: { prop: 'userName', type: 'index|enum|table|default|custom|date', func: '', key: 'BUG_REASON', value: 'email', label: 'userName' } }
 *   ],
 *   condition: {}
 * }
 */
router.post('/common/import', upload.single('file'), function(req, res, next) {
  var file = req.file;
  var params = req.body;
  params.filePath = './' + file.path;
  params.user = req.cookies['user'];
  params.config = JSON.parse(params.config);
  commonImportService.importData(params).then(() => {
      res.end()
  }).catch((err) => {
      err.httpStatusCode = 500
      return next(err)
  })
});

module.exports = router;